<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="Title">
                <a-input v-model="queryParam.title" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="Tag">
                <a-select v-model="queryParam.tag" placeholder="请选择" default-value="0">
                  <a-select-option v-for="tag in tags" :key="tag.id" :value="tag.id">{{ tag.name }} ({{ tag.count }})</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        :alert="true"
        :rowSelection="rowSelection"
        showPagination="auto"
        bordered
      >
        <template #serial="text, record, index">
          {{ index + 1 }}
        </template>
        <template #tags="tags">
          <a-tag v-for="tag in tags" :key="tag.id" :color="tag.id | TagColorFilter" >{{ tag.name }}</a-tag>
        </template>
        <template #subject="text, record">
          <router-link :to="{ name: 'BlogArticleEdit', params: { id: record.id } }">
            <a-button type="link" class="ant-btn-link">{{ text }}</a-button>
          </router-link>
        </template>

        <template #action="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handlePub(record)">发布</a>
        </template>
      </s-table>

    </a-card>
  </page-header-wrapper>
</template>

<script>
// import moment from 'moment'
import { mapActions, mapState } from 'vuex'
import { STable, Ellipsis } from '@/components'
import { getArticles, pubArticle } from '@/api/blog'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id'
  },
  {
    title: 'Title',
    dataIndex: 'title',
    scopedSlots: { customRender: 'subject' }
  },
  {
    title: 'Category',
    dataIndex: 'category',
    customRender: ({ name }) => name
  },
  {
    title: 'Tag',
    dataIndex: 'tags',
    scopedSlots: { customRender: 'tags' }
  },
  {
    title: 'Views',
    dataIndex: 'views',
    sorter: true
  },
  {
    title: 'Publish At',
    dataIndex: 'published_at',
    sorter: true
  },
  {
    title: 'Actions',
    dataIndex: 'action',
    width: '120px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'ArticleList',
  components: {
    STable,
    Ellipsis
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return getArticles(requestParameters)
          .then(res => {
            return res
          })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {
    statusFilter (type) {
      return type
    },
    TagColorFilter (tagId) {
      return ['pink', 'red', 'orange', 'green', 'cyan', 'blue', 'purple'][tagId % 7]
    }
  },
  created () {
    this.initTags()
    this.initCategories()
  },
  computed: {
    ...mapState({
      tags: state => state.blog.tags,
      categories: state => state.blog.categories
    }),
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    ...mapActions(['initTags', 'initCategories']),
    handleAdd () {
      this.$router.push({ name: 'BlogArticleNew' })
    },
    handleEdit (record) {
      this.$router.push({ name: 'BlogArticleEdit', params: { id: record.id } })
    },
    handlePub (record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
      pubArticle(record.id).then(() => this.$message.info('ok'))
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {}
    }
  }
}
</script>
